//
//  HYCalendarViewController.m
//  HYCalendar
//
//  Created by 王厚一 on 16/11/10.
//  Copyright © 2016年 why. All rights reserved.
//

#import "HYCalendarViewController.h"


static NSString * const calendarCell = @"CalendarCell";//cell的ide
static NSString * const calendarHeader = @"CalendarHeader";//header的ide

@interface HYCalendarViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView * collectionView;

@property (nonatomic, strong) NSDate * nowDate; //当前的时间
@property (nonatomic, strong) NSTimeZone * timeZone; //当地时区
@property (nonatomic, strong) NSCalendar * calendar; //当前日历
@property (nonatomic, strong) NSDateComponents * components; //当前日期的零件
@property (nonatomic, strong) NSDateFormatter * formatter; //时间书写格式
@property (nonatomic, strong) NSArray * weekdays; //日历星期格式

@end


@implementation HYCalendarViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];

}
#pragma mark - -----------lazy load-------------

- (NSTimeZone *)timeZone {
    //时区为中国上海
    if (!_timeZone) {
        _timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    }
    return _timeZone;
}

- (NSCalendar *)calendar {
    if (!_calendar) {
        _calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    }
    return _calendar;
}

- (NSDateComponents *)components {
    if (!_components) {
        _components = [[NSDateComponents alloc] init];
    }
    return _components;
}

- (NSDateFormatter *)formatter {
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        _formatter.dateFormat = @"yyyy-MM-dd";
    }
    return _formatter;
}

- (NSArray *)weekdays {
    //苹果日历每周第一天是周一，修改日历格式
    if (!_weekdays) {
        _weekdays = @[[NSNull null], @"0", @"1", @"2", @"3", @"4", @"5", @"6"];
    }
    return _weekdays;
}


#pragma mark - ------------获取时间方法-------------

/**根据当前时间获取当前和以后各有多少个月，0为当前月*/
- (NSDate *)getEarlierAndLaterDaysFromDate:(NSDate *)date withMonth:(NSInteger)month {
    
    NSDate * newDate = [NSDate date];
    
    NSDateComponents * components = [self getCurrentComponentWithDate:newDate];
    
    //获取section表示的每个月份
    NSInteger year = [components year];
    NSInteger month_n = [components month];
    
    //希望从哪年开始写日历 例如2016年
    
    NSInteger month_count = (year - 2016) * 12;
    
    //获取当前section代表的月份和现在月份的差值
    NSInteger months = month - month_count - month_n + 1;
    
    [self.components setMonth:months];
    
    //返回各月份的当前日期，如：2016-01-14，2016-02-14
    NSDate * ndate = [self.calendar dateByAddingComponents:self.components toDate:date options:0];
    
    
    return ndate;
    
}

/**获取每个单位内开始时间*/
- (NSString *)getBeginTimeInMonth:(NSDate *)date {
    
    NSTimeInterval count = 0;
    NSDate * beginDate = nil;
    NSCalendar * calendar = [NSCalendar currentCalendar];
    
    //返回日历每个月份的开始时间，类型是unitMonth
    BOOL findFirstTime = [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&beginDate interval:&count forDate:date];
    
    if (findFirstTime) {
        
        //日历设置为当前时区
        [self.calendar setTimeZone:self.timeZone];
        
        //标识为星期
        NSCalendarUnit unitFlags = NSCalendarUnitWeekday;
        
        //返回每个月第一天是周几
        NSDateComponents * com = [self.calendar components:unitFlags fromDate:beginDate];
        
        //更换为新的星期格式
        NSString * weekday = [self.weekdays objectAtIndex:[com weekday]];

        return weekday;
    }else {
        return @"";
    }
    
}

/**获取每个月多少天*/
- (NSInteger)getTotalDaysInMonth:(NSDate *)date {
    NSCalendar * calendar = [NSCalendar currentCalendar];
    
    //标识为day的单位在标识为month的单位中的格式，返回range
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
    
    return range.length;
}

/**获取当前日期格式*/
- (NSArray *)getTimeFormatArrayWithDate:(NSDate *)date andMonth:(NSInteger)month {
    NSDate * dateTime = [self getEarlierAndLaterDaysFromDate:self.nowDate withMonth:month];
    NSString * stringFormat = [self.formatter stringFromDate:dateTime];
    //通过“-”拆分日期格式
    NSLog(@"1 11111111 = == = = 获取当前日期格式 %@",[stringFormat componentsSeparatedByString:@"-"]);
    return [stringFormat componentsSeparatedByString:@"-"];
}

/**获取当前日期零件*/
- (NSDateComponents *)getCurrentComponentWithDate:(NSDate *)dateTime {
    NSCalendar * calendar = [NSCalendar currentCalendar];
    //日期拆分类型
    NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitDay;
    return [calendar components:unitFlags fromDate:dateTime];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    float fontsize = 14;
    fontsize = SCREEN_H < 667 ? 13 : 16;
    if (SCREEN_H == 667) {
        fontsize = 14;
    }
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"选择日期";
//    [self.navigationController.navigationItem setHidesBackButton:YES];

    UIButton * returnbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100.0/W_BASE*SCREEN_W, 44.0)];
    [returnbtn setTitle:@"\U0000e697" forState:UIControlStateNormal];
    returnbtn.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize+5];
    [returnbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem  = [[UIBarButtonItem alloc]initWithCustomView:returnbtn];
    returnbtn.titleLabel.textColor  = [UIColor blackColor];
    self.nowDate = [NSDate date];
    [returnbtn addTarget:self action:@selector(enterClick) forControlEvents:UIControlEventTouchUpInside];
    
    //设置布局
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(SCREEN_W / 7.0, SCREEN_W / 7.0 * 4 / 3.0);//item大小
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;//滚动方向
    flowLayout.headerReferenceSize = CGSizeMake(SCREEN_W, 50);//header大小
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);//边界距离
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    //注册
    [_collectionView registerNib:[UINib nibWithNibName:@"HYCalendarCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:calendarCell];
    [_collectionView registerNib:[UINib nibWithNibName:@"HYCalendarCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:calendarHeader];
    
    [self.view addSubview:_collectionView];
    
    
    // Do any additional setup after loading the view.
}

- (void)viewDidLayoutSubviews {
    
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
    NSInteger year = [dateComponent year];
    NSInteger month1 = [dateComponent month];
    NSInteger day = [dateComponent day];
    //    NSInteger hour = [dateComponent hour];
    //    NSInteger minute = [dateComponent minute];
    //    NSInteger second = [dateComponent second];
    
    NSInteger months = (year - 2016) * 12 + month1 - 1;
    
    
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:day inSection:months] atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
    
}




#pragma mark - ------------ DataSource && Delegate -------------

// headerView的size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    return CGSizeMake(SCREEN_W, 50);
}

// section的个数
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 100;
}

// item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    NSDate * dateTime = [self getEarlierAndLaterDaysFromDate:self.nowDate withMonth:section];
    NSString * firstTime = [self getBeginTimeInMonth:dateTime];
    NSInteger startDay = [firstTime integerValue];//开始时间，同样表示这个月开始前几天是空白
    NSInteger totalDays = [self getTotalDaysInMonth:dateTime];//某个月总天数
    
    return startDay + totalDays;
}

// cell代理方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HYCalendarCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:calendarCell forIndexPath:indexPath];
    
    NSDate * dateTime = [self getEarlierAndLaterDaysFromDate:self.nowDate withMonth:indexPath.section];
    
    //1号以前的负数日期不用显示
    NSInteger dayIndex = indexPath.row - [self getBeginTimeInMonth:dateTime].integerValue + 1;
    
    NSString * dayString = dayIndex > 0 ? [NSString stringWithFormat:@"%ld", dayIndex] : @"";
    
    cell.day.text = dayString;
    
    NSDateComponents * components = [self getCurrentComponentWithDate:dateTime];
    
    cell.type = self.itemType;
    
    [cell reloadCellWithFirstDay:self.firstDay andLastDay:self.lastDay andCurrentDay:@[[NSNumber numberWithInteger:[components year]], [NSNumber numberWithInteger:[components month]], [NSNumber numberWithInteger:dayIndex]] andSelectedColor:self.selectedColor andNormalColor:self.normalColor andMiddleColor:self.middleColor];
    return cell;
    
}

// 点击代理方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDate * dateTime = [self getEarlierAndLaterDaysFromDate:self.nowDate withMonth:indexPath.section];
    
    NSInteger dayIndex = indexPath.row - [self getBeginTimeInMonth:dateTime].integerValue + 1;

    NSDateComponents * components = [self getCurrentComponentWithDate:dateTime];
    
    
    //判断选择类型，单个类型选中后直接返回，否则选中两次返回
    if (self.chooseType == HYCalendarChooseSingle) {
        
        //年份和月份是通过section查找到，天数是通过row查到
        self.firstDay = @[[NSNumber numberWithInteger:[components year]],[NSNumber numberWithInteger:[components month]],[NSNumber numberWithInteger:dayIndex]];
        //由于单个选择直接刷新列表并返回
        [self.collectionView reloadData];
        [self goback];
    }
    
    if (self.chooseType == HYCalendarChooseDouble) {
        
        //由于上次选择时间有保留所以可能造成两个时间数组都有数据，如果可以点击并且后一个数组有数据说明是上次预留，清空数据。
        if (self.lastDay.count != 0) {
            self.firstDay = nil;
            self.lastDay = nil;
        }
        
        //只选择一项时值只刷新列表，全部选择时刷新并返回
        if (self.firstDay.count == 0) {
            self.firstDay = @[[NSNumber numberWithInteger:[components year]],[NSNumber numberWithInteger:[components month]],[NSNumber numberWithInteger:dayIndex]];
            [self.collectionView reloadData];
        }else {
            self.lastDay = @[[NSNumber numberWithInteger:[components year]],[NSNumber numberWithInteger:[components month]],[NSNumber numberWithInteger:dayIndex]];
            [self.collectionView reloadData];
            [self goback];
        }
    }
}

// header代理方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        HYCalendarCollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:calendarHeader forIndexPath:indexPath];
        
        //设置headerView的title
        [headerView showTimeLabelWithArray:(NSArray *)[self getTimeFormatArrayWithDate:self.nowDate andMonth:indexPath.section]];

        
        return headerView;
        
    }
    
    return nil;
}


#pragma mark - -----------------其他方法-----------------
- (void)enterClick{

    //延迟执行以下SEL中方法
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];

}
- (void)goback {
    
    //将两个时间返回
    if (self.getTime) {
        
        self.getTime(self.firstDay, self.lastDay);
        
    }
    
    //延迟执行以下SEL中方法
    [self performSelector:@selector(finalAction) withObject:nil afterDelay:0.5];
    
}

- (void)finalAction {
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

@end
